package com.teichmann.services;

import java.sql.Date;
import java.util.Collection;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import com.google.appengine.api.datastore.Key;
import com.teichmann.bo.Car;
import com.teichmann.bo.CarQueue;
import com.teichmann.jpa.util.EntityManagerHelper;

public class CarServices {

	public static int updateFoundCars(List<Car> cars) {

		EntityManager em = EntityManagerHelper.getEntityManager().createEntityManager();

		Query queryUrl = em.createNamedQuery("Car.findByURL");
		em.getTransaction().begin();
		for (Car car : cars) {
			// discover if the car already exists in database.
			Collection<Car> carReturned = null;

			if ((carReturned = queryUrl.setParameter(1, car.getUrl()).getResultList())
					.size() == 0) {
				em.persist(car);
			} else { // update it
				Car updated = ((List<Car>) carReturned).get(0);
				updated.setDataAtualizacao(new Date(System.currentTimeMillis()));
				em.merge(updated);
			}

		}
		em.getTransaction().commit();
		em.close();

		return cars.size();

	}

	public static List<CarQueue> findNotExecuted() {

		EntityManager em = EntityManagerHelper.getEntityManager().createEntityManager();

		Query queryUrl = em.createQuery("CarQueue.findNotExecuted");
		List<CarQueue> cars = queryUrl.getResultList();

		return cars;

	}

	public static void resetQueue() {
		EntityManager em = EntityManagerHelper.getEntityManager().createEntityManager();
		em.getTransaction().begin();

		Query queryUrl = em.createNativeQuery("Update CarQueue c set c.executed = 0");
		queryUrl.executeUpdate();

		em.getTransaction().commit();
	}

	public static void updateQueueItem(Key id) {
		EntityManager em = EntityManagerHelper.getEntityManager().createEntityManager();
		em.getTransaction().begin();

		Query queryUrl = em.createNamedQuery("Update CarQueue c set c.executed = 1 where c.id = ?1 ");
		queryUrl.setParameter(1, id);
		queryUrl.executeUpdate();

		em.getTransaction().commit();
	}

}
